$(function () {
    $("#jqGrid").jqGrid({
        url:baseURL+"sys/goods/unSoldlist" ,
        datatype: "json",
        colModel: [
            { label: '商品id', name: 'goodsId', width: 75,align:'center' , sortable: false},
            { label: '价格', name: 'price', width: 65, align:'center' , sortable: false},
            { label: '名称', name: 'name', width: 45,align:'center' , sortable: false},
            { label: '最少购买要求', name: 'leastNum', width: 60,align:'center'},
            { label: '详情图片', name: 'infoImg', width:75,align:'center' , sortable: false,formatter:function (value,option,row) {
                    return value==null?'-':'<a  onclick = "openImg(\''+value+'\')"> 查看图片 </a>';
                }},
            { label: '封面图片', name: 'coverImg', width: 60,align:'center',sortable: false,formatter:function (value,option,row) {
                    return value==null?'-':'<a  onclick = "openImg(\''+value+'\')"> 查看图片 </a>';
                }},
            { label: '轮播图', name: 'bannersList', width: 60,align:'center',sortable: false,formatter:function (value,options,row) {
                    return value.length==0?'-':'<a  onclick ="openCur('+JSON.stringify(row).replace(/"/g, '&quot;')+')"> 轮播预览 </a>';
                }},
            { label: '轮播图数量', name: 'bannersCount', width: 60,align:'center',sortable: false,formatter:function (value,options,row) {
                    return value==0?'-':value;
                }},
            { label: '商品类型', name: 'goodsType', width: 60,align:'center', sortable: false,formatter:function (value,optiosn,row) {
                    return value==1?"终端":value==0?"全部":"物料";
                }},
            { label: '顺序', name: 'sort', width: 45,align:'center', sortable: false},
            { label: '终端商家', name: 'terminalName', width: 65,align:'center',formatter:function (value,options,row) {
                    return value==null?"-":value;
                } , sortable: false},
            { label: '机具型号', name: 'model', width: 60,align:'center', sortable: false,formatter:function (value,options,row){
                    return value==null?"-":value;
                }},
            { label: '上架情况', name: 'isShow', width: 60,align:'center',formatter:function (value,options,row) {
                    return value==1?"售卖中":"未上架";
                } , sortable: false},
            { label: '上架时间', name: 'createTime', width: 65,align:'center', sortable: false},
            { label: '操作',name:'',formatter:function(value, options, row){
                    return '<span class = "btn btn-success btn-sm" onclick = "addBanner('+JSON.stringify(row).replace(/"/g, '&quot;')+')"> 添加轮播图 </span>&nbsp;&nbsp;'+
                        '<span class = "btn btn-success btn-sm" onclick = "handleBanner('+JSON.stringify(row).replace(/"/g, '&quot;')+')"> 整理轮播图 </span>&nbsp;&nbsp;'+
                        '<span class = "btn btn-success btn-sm" onclick = "updateGoods('+JSON.stringify(row).replace(/"/g, '&quot;')+')"> 下架 </span>&nbsp;&nbsp;';
                },align:'center' , sortable: false}
        ],
		viewrecords: true,
        height: 520,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect:true,
        multiboxonly:true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });

    bindType();
    loadBannerList();
});


var vm = new Vue({
    el:'#rrapp',
    data:{
        q:{
            terminalType:0,
            goodsType:0
        },
        showList: true,
        showAdd:false,
        title:null,
        addBanner:false,
        showUpdate:false,
        showBanner:false,
        updateBanner:false,
        terminalTypes:[],
        depts:[],
        initial:{
            terminalType:0,

        },

        filesList:[],
        goodsId:null,
        goods:{
            name:null,
            price:null,
            leastNum:null,
            goodsType:0,
            terminalType:0,

            model:null,
            isShow:null

        },
        banner:{
            goodsBannerId:null,
            bannerImg:null,
            sort:null
        }
    },
    methods: {
        query: function () {
            vm.reload();
        },
        clean: function () {
            vm.q={
                terminalType:0,
                goodsType:0
            };
            $("#jqGrid").jqGrid('setGridParam', {page: 1});
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.showAdd = true;
            vm.addBanner = false;
            vm.showBanner=false;
            vm.showUpdate=false;
            vm.title = "新增";
        },
        insertBanner: function () {
            let formdata = new FormData($('.addBanner')[0]);

            fileList.forEach(function (file) {
                console.log(file);
                formdata.append('file',file);
            });
            formdata.append("goodsId",$("#goodsId"));
            console.log(formdata.getAll("file"));

            $.ajax({
                url: baseURL+'sys/goods/addBanner',
                type: 'POST',
                datatype: 'json',
                data: formdata,
                cache:false,
                traditional: true,
                contentType: false,
                processData: false,
                success: function (r) {
                    if (r.code==0){
                        alert("成功");
                        vm.reload();
                    }
                }
            });

        },
        toUpdate:function(){
            let rowid=getSelectedRow();
            if(rowid==null){
                return;
            }
            let row=$("#jqGrid").jqGrid('getRowData', rowid);
            if(row==null){
                return;
            }

            $.get(baseURL+"sys/goods/findById/"+row.goodsId,(r)=>{
                console.log(r);
                vm.goods=r.goods;
                vm.showList=false;
                vm.showUpdate=true;
            })
        },
        update: function () {
            let formdata = new FormData($('.updateGoods')[0]);
            formdata.append("infoImg",$(".updateGoods input[name='infoImg']"));
            formdata.append("coverImg",$(".updateGoods input[name='coverImg']"));
            let inputEls=$(".updateGoods input[type='text']");
            for (let i=0; i< inputEls.length;i++){
                if($(inputEls[i]).val()==null || $(inputEls[i]).val()==''){
                    layer.msg("请完善商品信息");
                    return;
                }

                formdata.append($(inputEls[i]).attr("name"),$(inputEls[i]));
            }
            let selectEls=$(".updateGoods select");
            for (let i=0; i< selectEls.length;i++){
                if($(selectEls[i]).val()==null || $(selectEls[i]).val()==''){
                    layer.msg("请完善商品信息");
                    return;
                }

                formdata.append($(selectEls[i]).attr("name"),$(selectEls[i]));
            }
            $.ajax({
                url: baseURL+'sys/goods/updateGoods',
                type: 'POST',
                datatype: 'json',
                data: formdata,
                cache:false,
                traditional: true,
                contentType: false,
                processData: false,
                success: function (r) {
                    if (r.code==0){
                        alert("修改成功");
                        vm.reload();
                    }
                }
            });
        },
        reload: function () {
            vm.showList = true;
            vm.showAdd = false;
            vm.addBanner = false;
            vm.showBanner=false;
            vm.showUpdate=false;
            vm.updateBanner=false;
            let page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {
                    'terminalType':vm.q.terminalType,

                    'goodsType':vm.q.goodsType
                },
                page: page
            }).trigger("reloadGrid");
        },
        //ajax 提交表单,添加商品
        addgoods:function (){
            let formdata = new FormData($('.addgoods')[0]);
            if($("input[name='infoImg']").val()==null || $("input[name='infoImg']").val()==''){
                layer.msg("请选择详情图片");
                return;
            }
            if($("input[name='coverImg']").val()==null || $("input[name='coverImg']").val()==''){
                layer.msg("请选择封面图片");
                return;
            }
            formdata.append("infoImg",$(".addgoods input[name='infoImg']"));
            formdata.append("coverImg",$(".addgoods input[name='coverImg']"));
            let inputEls=$(".addgoods input[type='text']");
            for (let i=0; i< inputEls.length;i++){
                if($(inputEls[i]).val()==null || $(inputEls[i]).val()==''){
                    layer.msg("请完善商品信息");
                    return;
                }

                formdata.append($(inputEls[i]).attr("name"),$(inputEls[i]));
            }
            let selectEls=$(".addgoods select");
            for (let i=0; i< selectEls.length;i++){
                if($(selectEls[i]).val()==null || $(selectEls[i]).val()==''){
                    layer.msg("请完善商品信息");
                    return;
                }

                formdata.append($(selectEls[i]).attr("name"),$(selectEls[i]));
            }
            $.ajax({
                url: baseURL+'sys/goods/addGoods',
                type: 'POST',
                datatype: 'json',
                data: formdata,
                cache:false,
                traditional: true,
                contentType: false,
                processData: false,
                success: function (r) {
                    if (r.code==0){
                        alert("成功");
                        vm.reload();
                    }
                }
            });
        },
        addfile:function (msg,event) {
            thisvar=event.currentTarget;
            bannerfile = $.extend(true,{},thisvar);
            fileList.push(bannerfile);
        },
        commitUpdate:function () {
            let formdata = new FormData($('.updateBanner')[0]);
            formdata.append('file',$('.updateBanner input[name="file"]')[0]);
            formdata.append('sort',$('.updateBanner input[name="sort"]')[0]);
            formdata.append("goodsBannerId",$("#goodsBannerId")[0]);
            $.ajax({
                url: baseURL+'sys/goodsBanner/updateBanner',
                type: 'POST',
                datatype: 'json',
                data: formdata,
                cache:false,
                traditional: true,
                contentType: false,
                processData: false,
                success: function (r) {
                    if (r.code==0){
                        alert("成功");
                        vm.reload();
                    }else {
                        alert(r.msg)
                    }
                }
            });
        }
    }
});
var fileList=[];

//绑定terminalType
function bindType() {

        $.getJSON(baseURL + "sys/terminalType/list", function (r) {
            vm.$set(vm.terminalTypes, 0, {
                terminalType: 0,
                terminalName: "请选择类型"
            });
            for (let i = 0; i < r.page.length; i++) {
                vm.$set(vm.terminalTypes, (i + 1), r.page[i]);
            }
        })

}


//打开图片
function openImg(src){

    $("#goodsImg").attr("src",src);

    layer.open({
        type:1,
        title:"请选择",
        content:$("#goodsImg"),
        btn:['确定'],
        area:['720px','640px'],
        btn1:function (index) {
            layer.close(index);
        }

    })
}

//加载轮播图
function  openCur(row) {
    var bannersList=row.bannersList;
    $("#bannerContent").html("");

    var carouselDiv="";
    for(let i=0;i<bannersList.length;i++){
        carouselDiv+="<div><img src="+bannersList[i].bannerImg+" width=\"100%\" height=\"100%\"></div>";
    }
    $("#bannerContent").append(carouselDiv);
    layui.use('carousel', function(){
        let carousel = layui.carousel;
        //建造实例
        carousel.render({
            elem: '#goodBanner'
            ,width: '1125px' //设置容器宽度
            ,height:'630px'
            ,arrow: 'always' //始终显示箭头
            ,anim: 'default' //切换动画方式
            ,autoplay:true
        });
    });
    open();
}
//打开轮播图
function open() {
    layer.open({
        type:1,
        title:"请选择",
        content:$("#goodBanner"),
        btn:['确定'],
        area:['auto'],
        btn1:function (index) {
            $("#bannerContent").html("");
            layer.close(index);
        }

    })

}

//打开添加轮播图面板
function addBanner(row) {
    vm.showList=false;
    vm.showAdd=false;
    vm.addBanner=true;
    vm.showBanner=false;
    vm.showUpdate=false;
    vm.title="增加轮播图";
    $("#goodsId").val(row.goodsId);
}

//加载轮播图数据
function handleBanner(row) {
    vm.showList=false;
    vm.showAdd=false;
    vm.addBanner=false;
    vm.showBanner=true;
    vm.showUpdate=false;
    vm.title="轮播图列表";
    let page = $("#bannerList").jqGrid('getGridParam', 'page');
    $("#bannerList").jqGrid('setGridParam', {
        postData: {
            'goodsId':row.goodsId,
        },
        page: page,
        url:baseURL+"sys/goodsBanner/list",
        datatype:"json",
        caption:row.name,
    }).trigger("reloadGrid");

}

//加载轮播图列表
function loadBannerList() {
    $("#bannerList").jqGrid({
        datatype: "local",
        colModel: [
            { label: '轮播图id', name: 'goodsBannerId', width: 75,align:'center' , sortable: false},
            { label: '轮播图', name: 'bannerImg', width: 400, align:'center' , sortable: false,formatter:function (value,options,row) {
                    return '<img src="'+value+'" width="400" height="auto"></img>';
                }},
            { label: '播放顺序', name: 'sort', width: 45,align:'center' , sortable: false},
            { label: '创建时间', name: 'createTime', width: 60,align:'center', sortable: false,formatter:function (value,option,row) {
                    return new Date(value).Format("yyyy-MM-dd");
                }},
            { label: '操作',name:'goodsBannerId',formatter:function(value, options, row){
                    return '<span class = "btn btn-success btn-sm" onclick="deleteBanner('+value+')"> 删除 </span>&nbsp;&nbsp;'+
                        '<span class = "btn btn-success btn-sm" onclick="toUpdateBanner('+JSON.stringify(row).replace(/"/g, '&quot;')+')"> 修改 </span>&nbsp;&nbsp;';
                },align:'center' , sortable: false}
        ],
        viewrecords: true,
        height: 520,
        rowNum: 10,
        rowList : [10,30,50],
        rownumbers: true,
        rownumWidth: 25,
        autowidth:true,
        pager: "#bannerListPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page",
            rows:"limit",
            order: "order"
        },
        gridComplete:function(){
            //隐藏grid底部滚动条
            $("#bannerList").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
        }
    });
}


//修改商品
function updateGoods(goodsId) {
    confirm("确定上架此商品么",function () {
        $.get(baseURL+"sys/goods/sellGood/"+goodsId,r=>{
            if(r.code==0){
                layer.msg("上架成功");
                vm.reload();
            }else {
                layer.msg("上架成功");
                vm.reload();
            }
        })
    })

}


//删除轮播图
function deleteBanner(goodsBannerId) {
    $.get(baseURL+"sys/goodsBanner/delete/"+goodsBannerId,(r)=>{
            if(r.code==0){
                layer.msg("删除成功");
            }else{
                layer.msg("删除失败");
            }
        vm.reload();
    })
}


//修改
function toUpdateBanner(row) {
    console.log(row);
    vm.updateBanner=true;
    vm.showList = false;
    vm.showAdd = false;
    vm.addBanner = false;
    vm.showBanner=false;
    vm.showUpdate=false;
    vm.banner=row;
}
